package com.roy.sms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.roy.sms.model.Column;

@Repository
public class ColumnDao {

	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public Column add(Column column){
		getSession().save(column);
		return column;
	}
	
	public void update(Column column){
		getSession().update(column);
	}
	
	public void delete(int id){
		getSession().delete(load(id));
	}
	
	public Column load(int id){
		return (Column) getSession().load(Column.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Column> list(){
		return getSession().createQuery("from Column column").list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Column> list(int type){
		String hql = "select c from Column c where c.type=:type";
		return getSession().createQuery(hql).setParameter("type", type).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Column> listTop(int type){
		String hql = "select c from Column c where c.type=:type and c.parentColumn is NULL";
		return getSession().createQuery(hql).setParameter("type", type).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Column> listChildren(Column parent){
		String hql = "select c from Column c where c.parentColumn = :parent";
		return getSession().createQuery(hql).setParameter("parent", parent).list();
	}
	
}
